Page({
  data: {
    recipeId: null,
    recipeDetail: {},
    isLiked: false,
    isCollected: false,
    collecting: false,  // 防止重复点击收藏
    loading: true,
    // 评论相关
    comments: [],
    commentText: '',
    userAvatar: 'https://picsum.photos/60/60?random=999',
    showCommentInput: false, // 控制评论输入框显示
    userInfo: {} // 用于存储用户信息
  },

  onLoad(options) {
    const { id } = options;
    this.setData({
      recipeId: id
    });
    
    // 获取用户信息
    this.loadUserInfo();
    
    this.loadRecipeDetail(); // 加载真实接口数据
    this.loadComments(); // 评论可后续对接真实接口
  },

  // 加载用户信息
  loadUserInfo() {
    try {
      const userInfo = wx.getStorageSync('userInfo') || {};
      const userAvatar = wx.getStorageSync('userAvatar') || 'https://picsum.photos/60/60?random=999';
      
      this.setData({
        userInfo: userInfo,
        userAvatar: userInfo.avatarUrl || userAvatar
      });
    } catch (e) {
      console.error('获取用户信息失败', e);
    }
  },

  // 加载食谱详情（对接真实接口）
  loadRecipeDetail() {
    this.setData({
      loading: true
    });

    // 获取token
    let token = '';
    try {
      token = wx.getStorageSync('token');
      console.log('获取到的token:', token);
    } catch (e) {
      console.error('获取token失败', e);
    }

    wx.showLoading({
      title: '加载中...',
      mask: true
    });

    // 真实接口请求：路径拼接recipeId
    wx.request({
      url: `http://localhost/dev-api/recipes/recipes/${this.data.recipeId}`,
      method: 'GET',
      header: {
        'Authorization': token,
        'Content-Type': 'application/json'
      },
      success: (res) => {
        wx.hideLoading();

        if (res.data.code === 200 && res.data.data) {
          const apiData = res.data.data;
          
          // 根据媒体类型处理封面图和视频地址
          let imageUrl = 'https://picsum.photos/800/600?random=default'; // 默认封面图
          let videoUrl = ''; // 视频地址
          
          if (apiData.mediaType === 2) {
            // 视频类型：使用videoDescription作为封面图，coverUrl作为视频地址
            imageUrl = apiData.videoDescription 
              ? `http://localhost:8080${apiData.videoDescription}` 
              : 'https://picsum.photos/800/600?random=video';
            videoUrl = apiData.coverUrl 
              ? `http://localhost:8080${apiData.coverUrl}` 
              : '';
          } else if (apiData.mediaType === 1) {
            // 图片类型：使用coverUrl作为封面图
            imageUrl = apiData.coverUrl 
              ? `http://localhost:8080${apiData.coverUrl}` 
              : 'https://picsum.photos/800/600?random=image';
          }
          
          // 数据映射：接口字段 → 页面所需字段
          const recipeDetail = {
            id: apiData.id,
            type: apiData.mediaType || 1, // 1=图文，2=视频
            title: apiData.title || '未知菜谱',
            // 封面图
            imageUrl: imageUrl,
            // 视频地址
            videoUrl: videoUrl,
            // 作者信息
            authorName: apiData.users?.nickname || '未知作者',
            authorAvatar: apiData.users?.avatarUrl 
              ? `http://localhost:8080${apiData.users.avatarUrl}` 
              : 'https://picsum.photos/60/60?random=author',
            authorId: apiData.userId, // 用于跳转用户详情
            // 烹饪信息
            cookTime: apiData.cookTimeOptions?.name || '未知时间',
            difficulty: apiData.difficultyOptions?.name || '未知难度',
            viewCount: apiData.viewCount, // 接口未返回，暂用默认
            likes: apiData.collectCount || 0, // 用收藏数作为点赞数
            description: apiData.introduction || '暂无描述',
            // 食材列表映射
            ingredients: (apiData.recipeIngredients || []).map(ing => ({
              name: ing.name || '未知食材',
              amount: `${ing.quantity || ''}${ing.unit || ''}`, // 拼接数量+单位
              checked: false
            })),
            // 步骤列表映射
            steps: (apiData.recipeSteps || []).map(step => ({
              description: step.content || '暂无步骤说明',
              imageUrl: step.coverImg 
                ? `http://localhost:8080${step.coverImg}` 
                : 'https://picsum.photos/300/200?random=step'
            })),
            // 小贴士（接口未返回，暂空）
            tips: []
          };

          this.setData({
            recipeDetail,
            loading: false
          });

          // 检查用户是否已收藏此菜谱
          this.checkUserFavoriteStatus();
        } else {
          this.setData({
            loading: false
          });
          wx.showToast({
            title: '菜谱数据加载失败',
            icon: 'none'
          });
        }
      },
      fail: () => {
        wx.hideLoading();
        this.setData({
          loading: false
        });
        wx.showToast({
          title: '网络请求失败',
          icon: 'none'
        });
      }
    });
  },

  // 加载评论（对接真实接口）
  loadComments() {
    // 获取token
    let token = '';
    try {
      token = wx.getStorageSync('token');
    } catch (e) {
      console.error('获取token失败', e);
      return;
    }

    // 调用真实接口获取评论列表
    wx.request({
      url: `http://localhost/dev-api/recipes/recipes/comment/${this.data.recipeId}`,
      method: 'GET',
      header: {
        'Authorization': token,
        'Content-Type': 'application/json'
      },
      success: (res) => {
        if (res.data.code === 200) {
          const comments = (res.data.data || []).map(comment => ({
            id: comment.id,
            avatar: comment.users?.avatarUrl 
              ? `http://localhost:8080${comment.users.avatarUrl}` 
              : 'https://picsum.photos/60/60?random=user',
            username: comment.users?.nickname || '未知用户',
            time: this.formatTime(comment.createTime),
            content: comment.content,
            likeCount: comment.likeCount || 0,
            isLiked: false, // 暂时设为false，后续可以添加检查用户是否已点赞的逻辑
            userId: comment.userId
          }));

          this.setData({
            comments: comments
          });
        } else {
          console.error('获取评论失败:', res.data.msg);
        }
      },
      fail: (err) => {
        console.error('评论请求失败:', err);
        // 如果接口失败，使用默认评论数据
        const mockComments = [
          {
            id: 1,
            avatar: 'https://picsum.photos/60/60?random=100',
            username: '美食爱好者',
            time: '2小时前',
            content: '看起来很好吃，我也要试试！',
            likeCount: 12,
            isLiked: false
          },
          {
            id: 2,
            avatar: 'https://picsum.photos/60/60?random=101',
            username: '烘焙达人',
            time: '1天前',
            content: '步骤很详细，新手也能学会',
            likeCount: 8,
            isLiked: false
          }
        ];

        this.setData({
          comments: mockComments
        });
      }
    });
  },

  // 返回
  onBackTap() {
    wx.navigateBack();
  },

  // 点赞
  onLikeTap() {
    const isLiked = !this.data.isLiked;
    const recipeDetail = { ...this.data.recipeDetail };
    recipeDetail.likes = isLiked ? recipeDetail.likes + 1 : recipeDetail.likes - 1;
    
    this.setData({
      isLiked: isLiked,
      recipeDetail: recipeDetail
    });
  },

  // 收藏
  onCollectTap() {
    // 获取token
    let token = '';
    try {
      token = wx.getStorageSync('token');
    } catch (e) {
      console.error('获取token失败', e);
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
      return;
    }

    // 获取用户信息
    let userInfo = {};
    try {
      userInfo = wx.getStorageSync('userInfo') || {};
    } catch (e) {
      console.error('获取用户信息失败', e);
    }

    if (!userInfo.id) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
      return;
    }

    // 防止重复点击
    if (this.data.collecting) {
      return;
    }

    this.setData({
      collecting: true
    });

    wx.showLoading({
      title: '处理中...',
      mask: true
    });

    // 调用收藏/取消收藏接口
    wx.request({
      url: 'http://localhost/dev-api/recipes/recipes/favorite',
      method: 'POST',
      header: {
        'Authorization': token,
        'Content-Type': 'application/json'
      },
      data: {
        recipeId: this.data.recipeId,
        userId: userInfo.id
      },
      success: (res) => {
        wx.hideLoading();
        this.setData({
          collecting: false
        });
        
        if (res.data.code === 200) {
          const isFavorited = res.data.data;
          
          // 更新收藏状态
          this.setData({
            isCollected: isFavorited
          });

          // 更新收藏数量
          const recipeDetail = { ...this.data.recipeDetail };
          if (isFavorited) {
            recipeDetail.likes = (recipeDetail.likes || 0) + 1;
          } else {
            recipeDetail.likes = Math.max(0, (recipeDetail.likes || 0) - 1);
          }
          
          this.setData({
            recipeDetail: recipeDetail
          });

          wx.showToast({
            title: isFavorited ? '收藏成功' : '取消收藏',
            icon: 'success'
          });
        } else {
          wx.showToast({
            title: res.data.msg || '操作失败',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        wx.hideLoading();
        this.setData({
          collecting: false
        });
        console.error('收藏操作失败:', err);
        wx.showToast({
          title: '网络异常，请重试',
          icon: 'none'
        });
      }
    });
  },

  // 编辑菜谱（原关注按钮修改）
  onFollowTap() {
    wx.navigateTo({
      url: '/my/pages/editRecipe/editRecipe',
    })
  },

  // 分享
  onShareTap() {
    wx.showShareMenu({
      withShareTicket: true,
      menus: ['shareAppMessage', 'shareTimeline']
    });
  },

  // 评论
  onCommentTap() {
    // 聚焦到评论输入框
    this.setData({
      showCommentInput: true
    });
  },

  // 评论输入
  onCommentInput(e) {
    this.setData({
      commentText: e.detail.value
    });
  },

  // 提交评论
  onSubmitComment() {
    if (!this.data.commentText.trim()) {
      wx.showToast({
        title: '请输入评论内容',
        icon: 'none'
      });
      return;
    }

    // 获取token
    let token = '';
    try {
      token = wx.getStorageSync('token');
    } catch (e) {
      console.error('获取token失败', e);
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
      return;
    }

    // 获取用户信息
    let userInfo = {};
    try {
      userInfo = wx.getStorageSync('userInfo') || {};
    } catch (e) {
      console.error('获取用户信息失败', e);
    }

    wx.showLoading({
      title: '提交中...',
      mask: true
    });

    // 调用真实接口提交评论
    wx.request({
      url: 'http://localhost/dev-api/recipes/recipes/comment',
      method: 'POST',
      header: {
        'Authorization': token,
        'Content-Type': 'application/json'
      },
      data: {
        targetId: this.data.recipeId,
        targetType: 2,  // 2表示菜谱评论
        userId: userInfo.id,
        content: this.data.commentText
      },
      success: (res) => {
        wx.hideLoading();
        if (res.data.code === 200) {
          // 创建新评论对象
          const newComment = {
            id: res.data.data || Date.now(), // 使用接口返回的评论ID或时间戳
            avatar: userInfo.avatarUrl || this.data.userAvatar || 'https://picsum.photos/60/60?random=user',
            username: userInfo.nickname || userInfo.username || '我',
            time: '刚刚',
            content: this.data.commentText,
            likeCount: 0,
            isLiked: false,
            userId: userInfo.id || 1
          };

          // 添加到评论列表顶部
          const comments = [newComment, ...this.data.comments];
          this.setData({
            comments: comments,
            commentText: '',
            showCommentInput: false
          });

          wx.showToast({
            title: '评论成功',
            icon: 'success'
          });

          // 重新加载评论列表以确保数据同步
          setTimeout(() => {
            this.loadComments();
          }, 1000);
        } else {
          wx.showToast({
            title: res.data.msg || '评论失败',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        wx.hideLoading();
        console.error('评论提交失败:', err);
        
        // 如果接口失败，仍然在本地显示评论（模拟成功）
        const newComment = {
          id: Date.now(),
          avatar: userInfo.avatarUrl || this.data.userAvatar || 'https://picsum.photos/60/60?random=user',
          username: userInfo.nickname || userInfo.username || '我',
          time: '刚刚',
          content: this.data.commentText,
          likeCount: 0,
          isLiked: false,
          userId: userInfo.id || 1
        };

        const comments = [newComment, ...this.data.comments];
        this.setData({
          comments: comments,
          commentText: '',
          showCommentInput: false
        });

        wx.showToast({
          title: '评论已显示（网络异常）',
          icon: 'none'
        });
      }
    });
  },

  // 评论点赞
  onCommentLike(e) {
    const commentId = e.currentTarget.dataset.id;
    const commentIndex = this.data.comments.findIndex(comment => comment.id === commentId);
    
    if (commentIndex === -1) return;
    
    const comment = this.data.comments[commentIndex];
    const isLiked = !comment.isLiked;
    
    // 获取token
    let token = '';
    try {
      token = wx.getStorageSync('token');
    } catch (e) {
      console.error('获取token失败', e);
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
      return;
    }

    // 获取用户信息
    let userInfo = {};
    try {
      userInfo = wx.getStorageSync('userInfo') || {};
    } catch (e) {
      console.error('获取用户信息失败', e);
    }

    // 调用真实接口进行点赞/取消点赞
    wx.request({
      url: 'http://localhost/dev-api/recipes/recipes/comment/like',
      method: 'POST',
      header: {
        'Authorization': token,
        'Content-Type': 'application/json'
      },
      data: {
        id: commentId,
        userId: userInfo.id || 1
      },
      success: (res) => {
        if (res.data.code === 200) {
          // 更新本地评论数据
          const comments = [...this.data.comments];
          comments[commentIndex] = {
            ...comment,
            likeCount: isLiked ? comment.likeCount + 1 : comment.likeCount - 1,
            isLiked: isLiked
          };

          this.setData({
            comments: comments
          });

          wx.showToast({
            title: isLiked ? '点赞成功' : '取消点赞',
            icon: 'success'
          });
        } else {
          wx.showToast({
            title: res.data.msg || '操作失败',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        console.error('点赞操作失败:', err);
        wx.showToast({
          title: '操作失败',
          icon: 'none'
        });
      }
    });
  },

  // 点击作者头像 - 跳转到用户详情页
  onAuthorAvatarTap() {
    const authorId = this.data.recipeDetail.authorId || 1;
    wx.navigateTo({
      url: `/my/pages/user-detail/user-detail?id=${authorId}`
    });
  },

  // 点击评论用户头像 - 跳转到用户详情页
  onCommentUserAvatarTap(e) {
    const username = e.currentTarget.dataset.username;
    // 这里可以根据用户名或用户ID跳转，暂时跳转到用户详情页
    wx.navigateTo({
      url: `/my/pages/user-detail/user-detail?username=${username}`
    });
  },

  // 获取模拟用户ID
  getMockUserId(username) {
    const userMap = {
      '美食爱好者': 2,
      '烘焙达人': 3,
      '我': 1
    };
    return userMap[username] || 1;
  },

  // 食材勾选
  onIngredientCheck(e) {
    const index = e.currentTarget.dataset.index;
    const recipeDetail = { ...this.data.recipeDetail };
    recipeDetail.ingredients[index].checked = !recipeDetail.ingredients[index].checked;
    
    this.setData({
      recipeDetail: recipeDetail
    });
  },

  // 开始烹饪
  // onStartCookTap() {
  //   wx.showToast({
  //     title: '开始烹饪模式',
  //     icon: 'success'
  //   });
  // },

  // 格式化时间
  formatTime(date) {
    const now = new Date();
    const target = new Date(date);
    const diff = now - target;
    
    const minutes = Math.floor(diff / 60000);
    const hours = Math.floor(diff / 3600000);
    const days = Math.floor(diff / 86400000);
    
    if (minutes < 60) {
      return `${minutes}分钟前`;
    } else if (hours < 24) {
      return `${hours}小时前`;
    } else {
      return `${days}天前`;
    }
  },

  // 分享给朋友
  onShareAppMessage() {
    return {
      title: this.data.recipeDetail.title,
      path: `/my/pages/recipe-detail/recipe-detail?id=${this.data.recipeId}`,
      imageUrl: this.data.recipeDetail.imageUrl
    };
  },

  // 分享到朋友圈
  onShareTimeline() {
    return {
      title: this.data.recipeDetail.title
    };
  },

  // 预览图片
  previewImage(e) {
    const current = e.currentTarget.dataset.url;
    // 提取所有步骤图片+封面图作为预览列表
    const stepImages = this.data.recipeDetail.steps
      .filter(step => step.imageUrl)
      .map(step => step.imageUrl);
    const urls = [this.data.recipeDetail.imageUrl, ...stepImages];
    
    wx.previewImage({
      current: current,
      urls: urls
    });
  },

  // 检查用户是否已收藏此菜谱
  checkUserFavoriteStatus() {
    // 获取token
    let token = '';
    try {
      token = wx.getStorageSync('token');
    } catch (e) {
      console.error('获取token失败', e);
      return;
    }

    // 获取用户信息
    let userInfo = {};
    try {
      userInfo = wx.getStorageSync('userInfo') || {};
    } catch (e) {
      console.error('获取用户信息失败', e);
      return;
    }

    if (!userInfo.id) {
      return; // 用户未登录，不检查收藏状态
    }

    // 调用检查收藏状态接口
    wx.request({
      url: `http://localhost/dev-api/recipes/recipes/favorite/check/${this.data.recipeId}/${userInfo.id}`,
      method: 'GET',
      header: {
        'Authorization': token,
        'Content-Type': 'application/json'
      },
      success: (res) => {
        if (res.data.code === 200) {
          const isFavorited = res.data.data;
          this.setData({
            isCollected: isFavorited
          });
        }
      },
      fail: (err) => {
        console.error('检查收藏状态失败:', err);
      }
    });
  }
});